import http from '@/util/axios'
import type { Res, TPage } from '../types'
import * as T from './assetManagement_type'

export enum ApiPath {
  List = '/api/asset/resource/list', // 资源列表
  Create = '/api/asset/resource/create', // 创建资源
  Update = '/api/asset/resource/update', // 更新资源
  Edit = '/api/asset/resource/edit', // 编辑资源
  Get = '/api/asset/resource/detail', // 资源详情
  GetRelation = '/api/asset/resource/relation', // 资源关系
  Vers = '/api/asset/resource/versions', // 资源版本

  Remove= '/api/asset/resource/delete', // 删除资源
}

// 获得列表
export function getList(page: TPage, filter?: any, ): Promise<Res<T.TResourceList>> {
  const {create_time, update_time} = filter

  const params: {[key:string]: any} = {
    ...{
      page: 1,
      page_size: 10,
    },
    ...page, ...filter
  }
  console.log(`[ create_time ]=>`, filter)
  console.log(`[ create_time ]=>`, create_time)
  if (create_time && create_time.length === 2) {
    params.created_start_time = `${create_time[0]} 00:00:00`
    params.created_end_time = `${create_time[1]} 23:59:59`
  }
  if (update_time && update_time.length === 2) {
    params.update_start_time = `${update_time[0]} 00:00:00`
    params.update_end_time = `${update_time[1]} 23:59:59`
  }
  delete params.total
  delete params.create_time
  delete params.update_time
  delete params.all_version

  const paramArr: string[] = []
  for(const key in params) {
    if (!params[key]) continue
    paramArr.push(`${key}=${encodeURIComponent(params[key])}`)
  }
  return http.get(`${ApiPath.List}?${paramArr.join('&')}`)
}

// 创建资源
export function Create(data: T.TResourceItem): Promise<Res<number>> {
  return http.post(ApiPath.Create, data)
}

// 更新资源
export function Update(data: T.TResourceItem): Promise<Res<number>> {
  return http.post(ApiPath.Update, data)
}

// 编辑资源
export function Edit(data: T.TResourceItem): Promise<Res<number>> {
  return http.post(ApiPath.Edit, data)
}

// 获取资源详情
export function GetResourceInfo(id: number | string): Promise<Res<T.TResourceItem>> {
  return http.get(`${ApiPath.Get}?id=${id}`, {})
}

// 获取资源关系
export function GetRelation(id: number | string): Promise<Res<T.TResourceRelationItem[]>> {
  return http.get(`${ApiPath.GetRelation}?id=${id}`, {})
}

// 获取资源版本
export function GetVers(pageData: TPage, resource_code: string): Promise<Res<T.TResourceVerItem>> {
  const { page, page_size } = pageData
  if (!page || !page_size || !resource_code) {
    console.error('参数错误')
    return Promise.reject('参数错误')
  }
  return http.get(`${ApiPath.Vers}?page=${page}&page_size=${page_size}&resource_code=${resource_code}`, {})
}

// 删除资源
export function RemoveResource(resource_id: number): Promise<Res<number>> {
  return http.get(`${ApiPath.Remove}?resource_id=${resource_id}`, {})
}